package com.swgk.core.base.model.sugar;

import android.content.Context;
import android.content.ContextWrapper;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;

import java.io.File;
import java.io.IOException;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/7/21 11:31
 */
public class SugarContextWrapper extends ContextWrapper {
    private Context mContext;
    private String dirName;

    public SugarContextWrapper(Context base) {
        super(base);
        this.mContext = base;
    }

    public SugarContextWrapper(Context base, String dirName) {
        super(base);
        this.mContext = base;
        this.dirName = dirName;
    }

    @Override
    public File getDatabasePath(String name) {
        boolean sdExist = android.os.Environment.MEDIA_MOUNTED
                .equals(android.os.Environment.getExternalStorageState());
        if (!sdExist) {
            return null;
        } else {
            String dbDir = android.os.Environment.getExternalStorageDirectory()
                    .getAbsolutePath();
            dbDir += "/" + ((dirName == null || "".equals(dirName)) ?
                    mContext.getPackageName() : dirName);
            String dbPath = dbDir + "/" + name;
            File dirFile = new File(dbDir);
            if (!dirFile.exists())
                dirFile.mkdirs();

            boolean isFileCreateSuccess = false;
            File dbFile = new File(dbPath);
            if (!dbFile.exists()) {
                try {
                    isFileCreateSuccess = dbFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else
                isFileCreateSuccess = true;
            if (isFileCreateSuccess)
                return dbFile;
            else
                return null;
        }
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(
                getDatabasePath(name), null);
        return result;
    }

    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(
                getDatabasePath(name), null);
        return result;
    }
}
